﻿using JobColler.builder;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using JobColler.engine;
using System.Threading;
using System.Diagnostics;

namespace JobColler
{
    public partial class MainForm : Form
    {


        static Boolean running = false;

        static Boolean monitorRunning = false;

        static Queue<String> searchCompanyQueue = new Queue<String>();

        static StringBuilder currentSearchCompany = new StringBuilder();

        public MainForm()
        {
            Control.CheckForIllegalCrossThreadCalls = false;
            InitializeComponent();
        }
        [STAThread]
        private void button1_Click(object sender, EventArgs e)
        {
            if (SearchButton.Text.Equals("查询"))
            {
                running = true;
                SearchButton.Text = "停止";
                ResultListView.Items.Clear();
                Thread searchThread = new Thread(doSearch);
                searchThread.Start();
                return;
            }
            if (SearchButton.Text.Equals("停止"))
            {
                running = false;
                searchCompanyQueue.Clear();
                searchCompanyQueue = new Queue<string>();
                currentSearchCompany = new StringBuilder("");
                SearchButton.Text = "正在停止";
                if (!monitorRunning)
                {
                    SearchButton.Text = "查询";
                }
                return;
            }

        }


        private void doSearch()
        {
            SearchConfigBuilder config = builderConfig();
            for (int i = 1; i <= 500; i++)
            {
                if (!running)
                {
                    return;
                }
               
                List<CompanyInfoBuiler> results = SearchEngine.search(config, i);
                if (results == null || results.Count == 0)
                {
                    if (i == 1)
                    {
                        MessageBox.Show("无任何数据");
                    }

                    break;
                }
                List<ListViewItem> lvis = new List<ListViewItem>();

                List<CompanyInfoBuiler> builders = new List<CompanyInfoBuiler>();
                for (int v = 0; v < results.Count; v++)
                {
                    CompanyInfoBuiler result = results[v];
                    if (currentSearchCompany.ToString().Contains(result.CompName))
                    {
                        continue;
                    }
                    currentSearchCompany.AppendLine(result.CompName);
                    builders.Add(result);
                }

                for (int v = 0; v < builders.Count; v++)
                {
                    CompanyInfoBuiler builder = builders[v];
                    ListViewItem lvi = new ListViewItem();
                    lvi.Text = Convert.ToString(ResultListView.Items.Count + v + 1);
                    lvi.SubItems.Add(builder.CompName);
                    lvi.SubItems.Add("");
                    lvi.SubItems.Add("");
                    lvi.SubItems.Add(builder.Url);
                    lvis.Add(lvi);
                    searchCompanyQueue.Enqueue(Convert.ToString(ResultListView.Items.Count + v));
                }

                ResultListView.Items.AddRange(lvis.ToArray());
                if (!monitorRunning)
                {
                    Thread monitorThread = new Thread(threadMonitor);
                    monitorThread.Start();
                }
            }
        }
        private void threadMonitor()
        {
            if (monitorRunning)
            {
                return;
            }
            monitorRunning = true;
            while (true)
            {
                Thread.Sleep(500);
                int workerThreads = 0;
                int maxWordThreads = 0;
                //int   
                int compleThreads = 0;
                ThreadPool.GetAvailableThreads(out workerThreads, out compleThreads);
                ThreadPool.GetMaxThreads(out maxWordThreads, out compleThreads);
                //剩余线程
                int remain = maxWordThreads - workerThreads;
                for (int i = remain; i < 100; i++)
                {
                    if (searchCompanyQueue.Count < 1) { continue; }
                    String index = searchCompanyQueue.Dequeue();
                    if (String.IsNullOrEmpty(index))
                    {
                        continue;
                    }
                    if (ResultListView.Items.Count< (Convert.ToInt32(index)+1)) {
                        searchCompanyQueue.Enqueue(index);
                        continue;
                    }
                    ThreadPool.QueueUserWorkItem(new WaitCallback(exportCompanyInfo), Convert.ToInt32(index));
                }
                ThreadPool.GetAvailableThreads(out workerThreads, out compleThreads);
                ThreadPool.GetMaxThreads(out maxWordThreads, out compleThreads);
                if (workerThreads == maxWordThreads)
                {
                    monitorRunning = false;
                    break;
                }
            }
            monitorRunning = false;
            MessageBox.Show("执行完毕");
            SearchButton.Text = "查询";
        }
        private void exportCompanyInfo(object obj)
        {
            if (!running) {
                return;
            }
            Int32 index = Convert.ToInt32(obj);
            String url = ResultListView.Items[Convert.ToInt32(index)].SubItems[4].Text;
            CompanyInfoBuiler companyInfo = new CompanyInfoBuiler();
            companyInfo.Url = url;
            companyInfo = SearchEngine.searchCompanyInfo(companyInfo);
            ResultListView.Items[Convert.ToInt32(index)].SubItems[2].Text = companyInfo.CompSite;
            ResultListView.Items[Convert.ToInt32(index)].SubItems[3].Text = companyInfo.CompRemark;
            if (!String.IsNullOrEmpty(companyInfo.CompSite))
            {
                ResultListView.Items[Convert.ToInt32(index)].ForeColor = Color.Green;
            }
        }

        private void MainForm_Load(object sender, EventArgs e)
        {
            Icon icon = System.Drawing.Icon.ExtractAssociatedIcon(System.Diagnostics.Process.GetCurrentProcess().ProcessName + ".exe");
            this.Icon = icon;
            flushComBox(this);
        }

        private SearchConfigBuilder builderConfig()
        {
            SearchConfigBuilder config = new SearchConfigBuilder();
            config.Address = CityBox.Text;
            config.Companysize = CoSizeBox.Text;
            config.Cotype = CoTypeBox.Text;
            config.Degreefrom = DegreeBox.Text;
            config.Keyword = KeywordBox.Text.Trim();
            config.Remuner = RemunerBox.Text;
            config.Time = TimeBox.Text;
            config.Workyear = WorkBox.Text;
            return config;
        }

        private void flushComBox(Control control)
        {
            foreach (Control line in control.Controls)
            {
                if (line is Panel)
                {
                    flushComBox(line);
                    continue;
                }
                if (line is GroupBox)
                {
                    flushComBox(line);
                    continue;
                }
                if (line is ComboBox)
                {
                    ((ComboBox)line).SelectedIndex = 0;
                }
            }
        }



        private void 预览信息ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            try
            {
                System.Diagnostics.Process.Start(ResultListView.SelectedItems[0].SubItems[4].Text);
            }
            catch { }
        }

        private void 复制整行ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            try
            {
                Clipboard.SetDataObject(ResultListView.SelectedItems[0].SubItems[0].Text + ">>" + ResultListView.SelectedItems[0].SubItems[1].Text + ">>" + ResultListView.SelectedItems[0].SubItems[2].Text + ">>" + ResultListView.SelectedItems[0].SubItems[3].Text + ">>" + ResultListView.SelectedItems[0].SubItems[4].Text);
            }
            catch { }
        }

        private void 打开网址ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            try
            {
                String urlContent = ResultListView.SelectedItems[0].SubItems[2].Text;
                String[] urls = urlContent.Split(" ".ToCharArray());
                HashSet<String> urlSet = new HashSet<string>();
                for (int i = 0; i < urls.Length; i++)
                {
                    String url = urls[i];
                    if (String.IsNullOrEmpty(url))
                    {
                        continue;
                    }
                    url = url.ToLower().Trim();
                    if (!url.StartsWith("http://") && !url.StartsWith("https://"))
                    {
                        url = "http://" + url;
                    }
                    urlSet.Add(url);

                }
                foreach (string url in urlSet)
                {
                    System.Diagnostics.Process.Start(url);
                }

            }
            catch { }
        }

        private void MainForm_FormClosing(object sender, FormClosingEventArgs e)
        {
            DialogResult r = MessageBox.Show("Really want to exit?", "Remind", MessageBoxButtons.YesNo);
            if (r == DialogResult.Yes)
            {
                Process.GetCurrentProcess().Kill();
            }
            e.Cancel = true;
        }

        private void ResultListView_MouseDoubleClick(object sender, MouseEventArgs e)
        {
            打开网址ToolStripMenuItem_Click(sender, e);
        }
    }
}
